package com.appspot.bibtable.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.bibtable.PMF;
import com.appspot.bibtable.model.Reference;
import com.appspot.bibtable.model.ReferenceEntity;
import com.appspot.bibtable.model.format.DownloadFormatter;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class DownloadItemServlet extends HttpServlet
{
	private static final Logger logger = Logger.getLogger(DownloadItemServlet.class.getName());

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String[] keyStrings = request.getParameterValues("key");
		if (keyStrings == null)
		{
			keyStrings = new String[0];
		}
		String format = request.getParameter("format");
		DownloadFormatter formatter = null;
		
		try
		{
			formatter = DownloadFormatter.getInstance(format);
		}
		catch (IllegalArgumentException ex)
		{
			logger.severe(ex.getMessage());
			response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
			return;
		}

		response.setCharacterEncoding("UTF-8");
		formatter.setWriter(response.getWriter());

		response.setContentType(formatter.getContentType());
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Content-Disposition", "attachment; filename=\"bibtable" + formatter.getExtension() + "\"");
		
		PersistenceManager manager = PMF.get().getPersistenceManager();
		try
		{
			formatter.startDownload();
			for (int index = 0; index < keyStrings.length; index++)
			{
				try
				{
					Key key = KeyFactory.stringToKey(keyStrings[index]);
					ReferenceEntity entity = manager.getObjectById(ReferenceEntity.class, key);
					Reference reference = entity.getReference();
					formatter.startItem(reference, index);
					formatter.endItem(reference, index);
				}
				catch (JDOObjectNotFoundException ex)
				{
					logger.warning(ex.getMessage());
				}
			}
			formatter.endDownload();
		}
		finally
		{
			manager.close();
		}
	}
}
